﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AddRuleDAL;
using DBconnection;
using AddParameter_Form;


namespace AddRule
{
    public partial class AddRuleForm : Form
    {
         #region Data Members

        // Lists that are loaded from the DB
        string[] m_RulesList;
        string[] m_TypesList;
        string[] m_PropertiesList;
        string[] m_Connectors = {OR,AND};
        
        // Useful strings
        const string OR = "או";
        const string AND = "וגם";

        #endregion

        #region Properties

        /// <summary>
        /// The list of rules which should be added to the combo box
        /// </summary>
        public string[] RulesList
        {
            get
            {
                return this.m_RulesList;
            }
        }

        /// <summary>
        /// The list of types that exist in the DB
        /// </summary>
        public string[] TypesList
        {
            get
            {
                return this.m_TypesList;
            }
        }

        /// <summary>
        /// The list of properties associated with the used types
        /// </summary>
        public string[] PropertiesList
        {
            get
            {
                return this.m_PropertiesList;
            }
        }

        // The list of connectors possible between rules (basicly Or/And) in their hebrew names
        public string[] ConnectorsList
        {
            get
            {
                return this.m_Connectors;
            }
        }

        #endregion

        /// <summary>
        /// The creator of the form, Initialize here everything that has to be initialized in it.
        /// </summary>
        public AddRuleForm()
        {
            InitializeComponent();

            btnEnableEditing.Enabled = false;
            btval.Enabled = false;
            DB.OpenConnection();
            string[] Types = DB.GetAllClassesInDB();
            DB.CloseConnection();
            clmType.Items.Add(" ");
            clmType.Items.AddRange(Types);
            this.LoadRulesList();
        }





        /// <summary>
        /// Initializer for the rules list, this updates the list of rules from the DB and then refreshes the display.
        /// </summary>
        private void LoadRulesList()
        {
            // Refresh the rules list
            //m_RulesList = DBAccesor.GetRulesList();

            // Clear the current combo box and fill in the new rules
            rulePicker.Items.Clear();
            m_RulesList = DB.GetRulesList();
            if (m_RulesList.Length > 0)
            {
                rulePicker.Items.AddRange(m_RulesList);
                rulePicker.Enabled = true;
                rulePicker.SelectedIndex = 0;
            }
            else
            {
                rulePicker.Items.Add("EMPTY");
                rulePicker.SelectedIndex = 0;
                rulePicker.Enabled = false;
            }


            //rulePicker.Items.AddRange(RulesList);
           // BindingSource bs = new BindingSource();
           // bs.DataSource = m_RulesList;

            //rulePicker.DataSource = bs;

        }

        /// <summary>
        /// Initializer for the types list, this updates the list of rules from the DB and then refreshes the display.
        /// (might aswell be initialized only once because the types list only change when synchronizing with the data provider)
        /// Note that this list is used as source for the type combobox in the types grid.
        /// </summary>
        private void LoadTypes()
        {
            this.m_TypesList = DBAccesor.GetsTypes();

        }

        /// <summary>
        /// Load the rule itself, to fill the grids.
        /// </summary>
        private void LoadRule()
        {
            BindingSource bs = new BindingSource();
            bs.DataSource = m_RulesList;
            DBAccesor.GetRuleByName(rulePicker.SelectedText);
            grdRule.DataSource = bs;
            // TODO: here fill the grids and the properties list after GetRuleByName is decided.
        }

        /// <summary>
        /// Clear anything that is related to the rule
        /// </summary>
        private void ClearRule()
        {
            // Clear both grids from anything inside them
            //this.grdType.Rows.Clear();
            this.grdRule.Rows.Clear();

            // The properties list is related to the types chosen for the rule, 
            // therefor it shall be cleaned with the rule data
            this.m_PropertiesList = null;
            
        }


        
        private void btnEnableEditing_Click(object sender, EventArgs e)
        {
            pnlRule.Enabled = true;
            grdRule.Enabled = true;
            btnCancel.Enabled = true;
            grdType.Enabled = true;
            btnSaveRule.Enabled = true;
            btnEnableEditing.Enabled = false;
            btnNewRule.Enabled = false;
            rulePicker.Enabled = false;
            btval.Enabled = true;
        }

        private void btnNewRule_Click(object sender, EventArgs e)
        {
            DB.CreateNewRule(DB.CountOfRules()+1);
            LoadRulesList();
        }


        /// <summary>
        /// This events occurs after the user has fully changed the selection in the combo box 
        /// (opend combo box -> choose comething -> combo box closed)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rulePicker_SelectionChangeCommitted(object sender, EventArgs e)
        {

            grdRule.Rows.Clear();
            grdType.Rows.Clear();
            btnEnableEditing.Enabled = true;
            btval.Enabled = false;
            
            //Get the rule from DB
                string[] _RuleText = DB.GettingRule_Text(rulePicker.SelectedItem.ToString());
                if (!_RuleText[0].Equals("empty"))
                {
                    grdRule.Rows.Add(1);
                    int indexGridV = 0;

                    for (int i = 0; i < _RuleText.Length - 1; i++)
                    {
                        //string[] _SplitToParts = _RuleText[i].Split(' ');
                        switch (_RuleText[i])
                        {
                            case "IF":
                                grdRule[0, indexGridV].Value = _RuleText[i];
                                break;
                            case "OR": grdRule[0, indexGridV].Value = _RuleText[i];
                                break;
                            case "AND": grdRule[0, indexGridV].Value = _RuleText[i];
                                break;
                            case "THEN": grdRule[0, indexGridV].Value = _RuleText[i];
                                break;
                            case "NOT": grdRule[0, indexGridV].Value = _RuleText[i];
                                break;
                            case "ENDIF": grdRule[0, indexGridV].Value = "END_IF";
                                grdRule.Rows[indexGridV].Cells[1].Value = "";
                                grdRule.Rows[indexGridV].Cells[2].Value = "";
                                grdRule.Rows[indexGridV].Cells[3].Value = "";
                                indexGridV++;
                                grdRule.Rows.Add(1);
                                break;
                            case "ENDNOT": grdRule[0, indexGridV].Value = "END_NOT";
                                grdRule.Rows[indexGridV].Cells[1].Value = "";
                                grdRule.Rows[indexGridV].Cells[2].Value = "";
                                grdRule.Rows[indexGridV].Cells[3].Value = "";
                                indexGridV++;
                                grdRule.Rows.Add(1);
                                break;
                            default:
                                string[] _splitarr = _RuleText[i].Split(' ');
                                grdRule.Rows[indexGridV].Cells[1].Value = _splitarr[0];
                                grdRule.Rows[indexGridV].Cells[2].Value = _splitarr[1];
                                grdRule.Rows[indexGridV].Cells[3].Value = _splitarr[2];
                                if (i < _RuleText.Length - 2)
                                {
                                    grdRule.Rows.Add(1);
                                    
                                }
                                
                                indexGridV++;
                                break;
                        }
                        //if (_SplitToParts[0].Contains("END"))
                        //{
                        //    grdRule.Rows[indexGridV].Cells[0].Value = _SplitToParts[0].Replace("ENDIF","END_IF").Replace("ENDNOT","END_NOT");
                        //    grdRule.Rows[indexGridV].Cells[1].Value = "";
                        //    grdRule.Rows[indexGridV].Cells[2].Value = "";
                        //    grdRule.Rows[indexGridV].Cells[3].Value = "";
                        //    indexGridV++;
                        //}
                        //else
                        //{
                        //    grdRule.Rows[indexGridV].Cells[0].Value = _SplitToParts[0];
                        //    grdRule.Rows[indexGridV].Cells[1].Value = _SplitToParts[1];
                        //    grdRule.Rows[indexGridV].Cells[2].Value = _SplitToParts[2];
                        //    grdRule.Rows[indexGridV].Cells[3].Value = _SplitToParts[3];
                        //    indexGridV++;
                        //} SWITCH CASE
                    }
                }
                else
                {
                    grdRule.Rows.Add(1);
                }

            //--------------------//

            //Get rule contax from DB

                string type = DB.GettingRuleContax(rulePicker.SelectedItem.ToString());
                if (!type.Contains("empty"))
                {
                    grdType.Rows[0].Cells[0].Value=type;
                }


            //--------------------//
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            pnlRule.Enabled = false;
            grdRule.Enabled = false;
            btnCancel.Enabled = false;
            btnSaveRule.Enabled = false;
            grdType.Enabled = false;
            btnEnableEditing.Enabled = false;
            btnNewRule.Enabled = true;
            rulePicker.Enabled = true;
            btval.Enabled = false;
        }

        private void btnSaveRule_Click(object sender, EventArgs e)
        {
            string str = "";

            for (int i = 0; i < grdRule.Rows.Count-1; i++)
            {
                for (int j = 0; j < grdRule.Columns.Count; j++)
                {
                    if (grdRule.Rows[i].Cells[j].Value.ToString().Contains("END"))
                    {
                        str = str + grdRule.Rows[i].Cells[j].Value.ToString().Replace("_", string.Empty);
                        break;
                    }
                    if (grdRule.Rows[i].Cells[j].Value != null)
                    {
                        if (j == 0)
                        {
                            str = str + grdRule.Rows[i].Cells[j].Value.ToString() + ",";
                        }
                        else
                        {
                            str = str + grdRule.Rows[i].Cells[j].Value.ToString() + " ";
                        }
                    }
                }
      
                if (grdRule.Rows[i].Index < grdRule.Rows.Count - 1)
                {
                    str = str + ",";
                }
            }


            string Type = grdType[0,0].Value.ToString();
            DB.InsertRuleConIntoDB(rulePicker.SelectedItem.ToString(), Type);
            DB.InsertRuleIntoDB(rulePicker.SelectedItem.ToString(), str);

            pnlRule.Enabled = false;
            grdRule.Enabled = false;
            btnCancel.Enabled = false;
            btnSaveRule.Enabled = false;
            btnEnableEditing.Enabled = false;
            grdType.Enabled = false;
            btnNewRule.Enabled = true;
            rulePicker.Enabled = true;
            btval.Enabled = false;
        }

        private void btval_Click(object sender, EventArgs e)
        {

            int columnIndex = grdRule.CurrentCell.ColumnIndex;
            int rowIndex = grdRule.CurrentCell.RowIndex;
            if (columnIndex != 2 && columnIndex != 0)
            {
                grdRule.Rows[rowIndex].Cells[columnIndex].Value += "["+grdType.Rows[0].Cells[0].Value.ToString()+"."+cb_AddPrm.SelectedItem.ToString()+"]";
            }









            //using (AddParameterForm apf = new AddParameterForm(grdType.Rows[0].Cells[0].Value.ToString()))
            //{
            //    if (apf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            //    {
            //        int columnIndex = grdRule.CurrentCell.ColumnIndex;
            //        int rowIndex = grdRule.CurrentCell.RowIndex;
            //        if (columnIndex != 2 && columnIndex != 0)
            //        {
            //            grdRule.Rows[rowIndex].Cells[columnIndex].Value += apf.SelecetedText;
            //        }
            //    }
            //}
        }

        private void grdRule_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (grdRule.CurrentCell != null && grdRule.CurrentCell.Value != null)
            {
                if (grdRule.CurrentCell.Value.ToString().Contains("END"))
                {
                    grdRule.CurrentRow.Cells[1].ReadOnly = true;
                    grdRule.CurrentRow.Cells[2].ReadOnly = true;
                    grdRule.CurrentRow.Cells[3].ReadOnly = true;
                    grdRule.CurrentRow.Cells[1].Value = "";
                    grdRule.CurrentRow.Cells[2].Value = "";
                    grdRule.CurrentRow.Cells[3].Value = "";
                }
                else
                {
                    grdRule.CurrentRow.Cells[1].ReadOnly = false;
                    grdRule.CurrentRow.Cells[2].ReadOnly = false;
                    grdRule.CurrentRow.Cells[3].ReadOnly = false;
                }
            }
        }

        private void grdType_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            grdType.Enabled = false;
            string [] Prms=DB.GetParameters(grdType.Rows[0].Cells[0].Value.ToString());
            cb_AddPrm.Items.Clear();
            cb_AddPrm.Items.AddRange(Prms);
        }



       
        
    }
}
